import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Layout from '@/layout/index.vue'
import asyncRoute from '@/router/asyncRoutes';

Vue.use(VueRouter)

/*通用routers*/
export const currencyRoutes = [
  {
    path: '/login',
    name: 'Login',
    meta: {title: '登录页',},
    hidden: true,
    component: resolve => require(['@/views/login'], resolve),
  },
  {
    path: '/',
    name: 'Index',
    component: Layout,
    redirect: '/home',
    hidden: true,
    children: [
      {
        path: 'home',
        name: 'Home',
        meta: {title: '首页', icon: 'el-icon-s-home',},
        hidden: false,
        component: resolve => require(['@/views/home'], resolve),
      },
      {
        path: "icons",
        name: 'icons',
        hidden: false,
        meta: { title: 'icon图标', icon: "el-icon-s-goods", },
        component: resolve => require(['@/views/icons'], resolve),
      },
    ]
  },
  {
    path: "/dataScreen",
    name: 'dataScreen',
    meta: { title: "数据大屏", icon: "el-icon-s-marketing", },
    hidden: false,
    component: resolve => require(['@/views/dataScreen'], resolve),
  },
]

/*动态添加routers*/
export const addRouter = asyncRoute;

const createRouter = () => new VueRouter({
  mode: 'hash', //history:浏览器地址栏，没有#
  scrollBehavior: () => ({ x: 0, y: 0 }),
  routes: currencyRoutes.concat(addRouter)
  // routes: currencyRoutes
})

const router = createRouter();

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
// 在index.js 里面写入下面的代码即可解决
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err);
};
// 重置路由
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

// 检查是否存在于免登陆白名单
function inWhiteList(toPath) {
  const whiteList = ['/login', '/register', '/404']
  const path = whiteList.find((value) => {
    return value === toPath
  })
  return !!path
}

// 导航守卫
router.beforeEach(async (to, from, next) => {
  //获取本地存储的token
  store.state.token = localStorage.getItem('userToken');
  //判断是否有标题  该操作可以再监听路由时候处理 watch:{'$route'(to,from){xxx操作}}
  if(to.meta.title) {
    document.title = to.meta.title
  }
  // 判断该路由是否需要登录权限
  // if(to.path === '/login') {
  if(inWhiteList(to.path)) {
    next()
  }
  else {
    // 通过vuex state获取当前的token是否存
    if(store.state.token) {
      // console.log('有token时候', to, from, next)
      // currencyRoutes.concat(addRouter)
      next();
    } else {
      // console.log('没有token时候', to)
      next({
        path: '/login',
        // query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
})

export default router
